package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.RoleException;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService{

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        List<Role> roles = roleMapper.findPage(queryPageBean.getQueryString());

        return PageResult.builder().rows(roles).total(page.getTotal()).build();

    }

    @Override
    public void add(Role role) {

        roleMapper.add(role);

        Integer roleId = role.getId();

        roleMapper.setPerIdAndRoleId(roleId,role.getPermissionIds());

    }

    @Override
    public void deletebyid(Integer id) throws RoleException {

        int count = roleMapper.findConutByRole(id);

        if(count>0){
            throw new RoleException("存在引用 不能删除");
        }

        roleMapper.deleteAssociation(id);

        roleMapper.deletebyid(id);

    }

    @Override
    public Map findbyid4updata(Integer id) {
        HashMap<String, Object> map = new HashMap<>();

        Role role = roleMapper.findRoleById(id);

        String keyword = role.getKeyword();
        keyword = keyword.replace("ROLE_","");
        role.setKeyword(keyword);

        List<Permission> permissions = permissionMapper.findall();

        List<Integer> PerIds = roleMapper.findPerIdsByRoleId(id);
        role.setPermissionIds(PerIds);

        map.put("role",role);
        map.put("allPers",permissions);

        return map;
    }

    @Override
    public void edit(Role role) {
        roleMapper.edit(role);

        roleMapper.deleteAssociation(role.getId());

        roleMapper.setPerIdAndRoleId(role.getId(),role.getPermissionIds());
    }

    @Override
    public List<Role> findAll() {

        return roleMapper.findAll();
    }
}
